<?php

namespace app\admin\controller;

use think\Validate;
use think\Db;
use app\models\{Banner, Region, PlatClass, Config, PlatSons, Withdraw, Agent, Business, BusinessArea, Goods, GoodsSpec, SystemGoodsSpec, SystemGoods, ConvenClass, Conven, Rebot};

class System extends Base
{

    public function system_daoru()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'business' => 'require'
            ], [
                'id.require' => '服务名称不能为空',
                'business.require' => '商家不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $daoru = (new Goods())->where(['systemid' => $data['id'], 'businessid' => $data['business'], 'isdel' => 1, 'isSale' => 1])->find();
            // if (!empty($daoru)) {
            //     return json(['code' => 1, 'data' => [], 'msg' => '服务已导入，无需重复导入']);
            // }
            $model = new SystemGoods();
            $specmodel = new SystemGoodsSpec();
            $results = $model->where(['id' => $data['id'], 'isdel' => 1, 'isSale' => 1])->find();
            if (empty($results)) {
                return json(['code' => 1, 'data' => [], 'msg' => '服务不存在或已下架']);
            }
            $speclist = $specmodel->where(['isdel' => 1, 'goodid' => $results['id']])->select();
            if (empty($speclist)) {
                return json(['code' => 1, 'data' => [], 'msg' => '导入商品规格为空']);
            }
            $goods = [];
            $goodsspec = [];
            $goods = $results->toArray();
            $goods['systemid'] = $results['id'];
            $goods['businessid'] = $data['business'];
            unset($goods['id']);
            Db::startTrans();
            try {
                $id = (new Goods())->insertGetId($goods);
                foreach ($speclist as $lists) {
                    $spec = $lists;
                    $spec['businessid'] = $data['business'];
                    $spec['goodid'] = $id;
                    unset($spec['id']);
                    $goodsspec[] = $spec->toArray();
                }
                (new GoodsSpec())->saveAll($goodsspec);
                Db::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                Db::rollback();
                return json(['code' => 1, 'status' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            }
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
    }

    public function conven()
    {
        $list = (new Conven())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $admin = $this->request->admin;
        switch ($admin['type']) {
            case '2':
                $list = $list->where(['city' => $admin['city']]);
                break;
            case '3':
                $list = $list->where(['area' => $admin['area']]);
                break;
            case '4':
                $list = $list->where(['street' => $admin['street']]);
                break;
            default:
                break;
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        if (!empty($data['classid'])) {
            $list = $list->where(['classid' => $data['classid']]);
        }
        $list = $list->paginate(10)->each(function ($row) {
            $row['city'] = array_filter(explode(',', $row['city']));
            $row['area'] = array_filter(explode(',', $row['area']));
            $row['street'] = array_filter(explode(',', $row['street']));
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['class_name'] = (new ConvenClass())->where('id', $row['classid'])->value('name');
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        $ConvenClass = (new ConvenClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'convenclass' => $ConvenClass
        ]);
    }

    public function conven_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require|in:1,2,3,4'
            ], [
                'title.require' => '不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            switch ($data['type']) {
                case '1':
                    $data['province'] = $data['province'] ?? 0;
                    $data['city'] = $data['city'] ?? 0;
                    $data['area'] = $data['area'] ?? 0;
                    $data['street'] = $data['street'] ?? 0;
                    break;
                case '2':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    $data['area'] = 0;
                    $data['street'] = 0;
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            if (!empty($data['id'])) {
                $res = (new Conven())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Conven())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Conven())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            if (!empty($row)) {
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                $carent = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->find();
                $area = (new Region())->where(['level' => 3, 'parent_id' => $carent['id']])->select();
                $aarent = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->find();
                $street = (new Region())->where(['level' => 4, 'parent_id' => $aarent['id']])->select();
            }
            $ConvenClass = (new ConvenClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'convenclass' => $ConvenClass

            ]);
        }
    }

    public function conven_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new Conven())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '项目不存在，请重试']);
            }
            $res = (new Conven())->where('id', $id)->delete();
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function goodslist()
    {
        $model = new SystemGoods();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        $ptsons = [];
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['platclassid'])) {
            $ptsons = (new PlatSons())->where('isshow', 1)->where('platclassid', $data['platclassid'])->order(['sort' => 'desc', 'id' => 'desc'])->select();
            $results = $results->where('classid', $data['platclassid']);
        }
        if (!empty($data['sonsid'])) {
            $results = $results->where('sonsid', $data['sonsid']);
        }
        $results = $results->where(['type' => [1, 2]])->paginate(10, false, ['query' => $this->request->param()]);
        $platclass = (new PlatClass())->where('isshow', 1)->where('type', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true) ?? [];
            $result['class_name'] = (new PlatClass())->where('id', $result['classid'])->value('name');
            $result['sons_name'] = (new PlatSons())->where('id', $result['sonsid'])->value('name');
            $result['goodspec'] = (new SystemGoodsSpec())->where(['isdel' => 1, 'goodid' => $result['id']])->order('is_default desc')->find();
        }
        return view(null, [
            'list' => $results,
            'platclass' => $platclass,
            'ptsons' => $ptsons,
        ]);
    }


    public function goodslist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require|in:1,2',
                'descs' => 'require',
                'images' => 'require',
                'classid' => 'require',
                'sonsid' => 'require',
                'spec' => 'require'
            ], [
                'title.require' => '服务名称不能为空',
                'type.require' => '服务类型不能为空',
                'type.in' => '服务类型不正确',
                'descs.require' => '服务描述不能为空',
                'images.require' => '图片不能为空',
                'classid.require' => '平台大类不能为空',
                'sonsid.require' => '平台分类不能为空',
                'spec.require' => '规格必须填写'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['parpam'])) {
                $data['parpam'] = json_encode($data['parpam'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            $goodmodel = new SystemGoods();
            $platsonsmodel = new PlatSons();
            $specmodel = new SystemGoodsSpec();
            //查找分类是否存在
            $platsons = $platsonsmodel->where(['id' => $data['sonsid']])->find();
            if (empty($platsons)) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家分类不存在']);
            }
            $data['classid'] = $platsons['platclassid'];
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new SystemGoods();
            $specmodel = new SystemGoodsSpec();
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $platsons = [];
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['parpam'] = json_decode($results['parpam'], true) ?? [];
                $results['speclist'] = $specmodel->order('is_default desc')->where(['isdel' => 1, 'goodid' => $results['id']])->select();
                $platsons = (new PlatSons())->where('platclassid', $results['classid'])->where('isshow', 1)->select();
            }
            $platclass = (new PlatClass())->where('isshow', 1)->select();
            return view(null, [
                'row' => $results,
                'platclass' => $platclass,
                'platsons' => $platsons
            ]);
        }
    }

    public function withdraw()
    {
        $results = (new Withdraw())->order('id desc');
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if ($result['type'] == 1) {
                $result['type_name'] = (new Business())->where('id', $result['user_id'])->value('title');
            }
            if ($result['type'] == 2) {
                $result['type_name'] = (new Agent())->where('id', $result['user_id'])->value('nickname');
            }
            if ($result['status'] == 1) {
                $result['status_text'] = '待审核';
            }
            if ($result['status'] == 2) {
                $result['status_text'] = '审核通过';
            }
            if ($result['status'] == 3) {
                $result['status_text'] = '平台或代理取消';
            }
        }
        return view(null, [
            'list' => $results
        ]);
    }


    public function withdraw_str()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require'
        ], [
            'id.require' => 'ID不能为空'
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'msg' =>  $validate->getError()]);
        }
        $withdraw = (new Withdraw())->order('id desc')->where(['id' => $data['id'], 'status' => 1])->find();
        if (empty($withdraw)) {
            return json(['status' => 1, 'msg' =>  '记录不可操作']);
        }
        Db::startTrans();
        try {
            if ($withdraw['type'] == 1) {
                (new Business())->MoneyEdit($withdraw['user_id'], 2, $withdraw['money'], '商户提现平台驳回', 0);
            }
            if ($withdraw['type'] == 2) {
                (new Agent())->MoneyEdit($withdraw['user_id'], 3, $withdraw['money'], '代理提现平台驳回', 0);
            }
            (new Withdraw())->where(['id' => $data['id'], 'status' => 1])->update(['status' => 3]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'code' => 1, 'msg' => '操作失败']);
        }
        return json(['status' => 0, 'code' => 0, 'msg' => '操作成功']);
    }

    public function withdraw_str2()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require'
        ], [
            'id.require' => 'ID不能为空'
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'msg' =>  $validate->getError()]);
        }
        $withdraw = (new Withdraw())->order('id desc')->where(['id' => $data['id'], 'status' => 1])->find();
        if (empty($withdraw)) {
            return json(['status' => 1, 'msg' =>  '记录不可操作']);
        }
        Db::startTrans();
        try {
            (new Withdraw())->where(['id' => $data['id'], 'status' => 1])->update(['status' => 2]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 1, 'code' => 1, 'msg' => '操作失败']);
        }
        return json(['status' => 0, 'code' => 0, 'msg' => '操作成功，请线下转账']);
    }

    public function platsons()
    {
        $list = (new PlatSons())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['name'])) {
            $list = $list->where('name', 'like', '%' . $data['name'] . '%');
        }
        if (!empty($data['platclassid'])) {
            $list = $list->where('platclassid', $data['platclassid']);
        }
        $platclass = (new PlatClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        $list = $list->paginate(10);
        foreach ($list as $lists) {
            $lists['class_name'] = (new PlatClass())->where('id', $lists['platclassid'])->value('name');
        }
        return view(null, [
            'list' => $list,
            'platclass' => $platclass
        ]);
    }

    public function platsons_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'images' => 'require',
                'platclassid' => 'require',
            ], [
                'name.require' => '服务类型不能为空',
                'images.require' => '图片路径不能为空',
                'platclassid.require' => '所属分类不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $admin = $this->request->admin;
            //管理员区域权限判断
            if ($admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '无操作权限']);
            }
            if (!empty($data['id'])) {
                $res = (new PlatSons())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new PlatSons())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new PlatSons())->where('id', $id)->find();
            if (empty($row)) {
                $row['platclassid'] = $this->request->get('platclassid/d', 0);
            }
            $platclass =  (new PlatClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
            return view('', [
                'row' => $row,
                'platclass' => $platclass

            ]);
        }
    }

    public function platsons_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除服务类型']);
            }
            $banner = (new PlatSons())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '服务类型不存在，请重试']);
            }
            $admin = $this->request->admin;
            //管理员区域权限判断
            if ($admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '无操作权限']);
            }
            $res = (new PlatSons())->where('id', $id)->update(['isshow' => 2]);
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function convenclass()
    {
        $list = (new ConvenClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['name'])) {
            $list = $list->where('name', 'like', '%' . $data['name'] . '%');
        }
        $list = $list->paginate(10);
        return view(null, [
            'list' => $list
        ]);
    }

    public function convenclass_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
            ], [
                'name.require' => '分类名称不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['id'])) {
                $res = (new ConvenClass())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new ConvenClass())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new ConvenClass())->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function convenclass_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new ConvenClass())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '类目不存在，请重试']);
            }
            $res = (new ConvenClass())->where('id', $id)->update(['isshow' => 2]);
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function PlatClass()
    {
        $list = (new PlatClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc']);
        $data = $this->request->get();
        if (!empty($data['name'])) {
            $list = $list->where('name', 'like', '%' . $data['name'] . '%');
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        $list = $list->paginate(10);
        return view(null, [
            'list' => $list
        ]);
    }

    public function platclass_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'images' => 'require'
            ], [
                'name.require' => '分类名称不能为空',
                'images.require' => '图片路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $admin = $this->request->admin;
            //管理员区域权限判断
            if ($admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '无操作权限']);
            }
            if (!empty($data['id'])) {
                $res = (new PlatClass())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new PlatClass())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new PlatClass())->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function platclass_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new PlatClass())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '项目不存在，请重试']);
            }
            $admin = $this->request->admin;
            //管理员区域权限判断
            if ($admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '无操作权限']);
            }
            $res = (new PlatClass())->where('id', $id)->update(['isshow' => 2]);
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function banner()
    {
        $list = (new Banner())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $admin = $this->request->admin;
        switch ($admin['type']) {
            case '2':
                $list = $list->where(['city' => $admin['city']]);
                break;
            case '3':
                $list = $list->where(['area' => $admin['area']]);
                break;
            case '4':
                $list = $list->where(['street' => $admin['street']]);
                break;
            default:
                break;
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        $list = $list->paginate(10)->each(function ($row) {
            $row['city'] = array_filter(explode(',', $row['city']));
            $row['area'] = array_filter(explode(',', $row['area']));
            $row['street'] = array_filter(explode(',', $row['street']));
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street
        ]);
    }

    public function banner_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'type' => 'require|in:1,2,3,4',
                'url' => 'require'
            ], [
                'title.require' => '轮播图备注信息不能为空',
                'type.require' => '轮播图类型不能为空',
                'type.in' => '轮播图类型不正确',
                'url.require' => '图片路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            $admin = $this->request->admin;
            if ($admin['type'] >= $data['type'] && $admin['type'] != 1) {
                return json(['status' => 1, 'msg' => '添加类型权限不足,请选择其它下级类型']);
            }
            switch ($data['type']) {
                case '1':
                    $data['province'] = $data['province'] ?? 0;
                    $data['city'] = $data['city'] ?? 0;
                    $data['area'] = $data['area'] ?? 0;
                    $data['street'] = $data['street'] ?? 0;
                    break;
                case '2':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    $data['area'] = 0;
                    $data['street'] = 0;
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            //管理员区域权限判断
            switch ($admin['type']) {
                case '1':
                    break;
                case '2':
                    //验证城市是否在范围内
                    $city = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->find();
                    if (empty($city)) {
                        return json(['status' => 1, 'msg' => '城市信息不存在']);
                    }
                    if (!in_array($data['city'], $admin['city'])) {
                        return json(['status' => 1, 'msg' => '当前城市不在管理范围内']);
                    }
                    break;
                case '3':
                    //验证城市是否在范围内
                    $area = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->find();
                    if (empty($area)) {
                        return json(['status' => 1, 'msg' => '区域信息不存在']);
                    }
                    if (!in_array($data['area'], $admin['area'])) {
                        return json(['status' => 1, 'msg' => '当前区域不在管理范围内']);
                    }
                    break;
                case '4':
                    //验证城市是否在范围内
                    $street = (new Region())->where(['level' => 4, 'id' => $data['street']])->find();
                    if (empty($street)) {
                        return json(['status' => 1, 'msg' => '街道信息不存在']);
                    }
                    if (!in_array($data['street'], $admin['street'])) {
                        return json(['status' => 1, 'msg' => '当前街道不在管理范围内']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            if (!empty($data['id'])) {
                $res = (new Banner())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Banner())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Banner())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            return view('', [
                'row' => $row,
                'province' => $province
            ]);
        }
    }

    public function banner_del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id/d', 0);
            if (empty($id)) {
                return json(['status' => 1, 'msg' => '请选择删除项目']);
            }
            $banner = (new Banner())->where('id', $id)->find();
            if (empty($banner)) {
                return json(['status' => 1, 'msg' => '项目不存在，请重试']);
            }
            $admin = $this->request->admin;
            //管理员区域权限判断
            switch ($admin['type']) {
                case '1':
                    break;
                case '2':
                    //验证城市是否在范围内
                    if (!in_array($banner['city'], $admin['city'])) {
                        return json(['status' => 1, 'msg' => '不在管理范围内']);
                    }
                    break;
                case '3':
                    //验证城市是否在范围内
                    if (!in_array($banner['area'], $admin['area'])) {
                        return json(['status' => 1, 'msg' => '不在管理范围内']);
                    }
                    break;
                case '4':
                    //验证城市是否在范围内
                    if (!in_array($banner['street'], $admin['street'])) {
                        return json(['status' => 1, 'msg' => '不在管理范围内']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '管理员类型错误']);
                    break;
            }
            $res = (new Banner())->where('id', $id)->delete();
            if ($res) {
                return json(['status' => 0, 'msg' => '操作成功']);
            }
            return json(['status' => 1, 'msg' => '操作失败']);
        }
    }

    public function config()
    {
        $list = (new Config())->paginate(10);
        foreach ($list as $lists) {
            if ($lists['name'] == 'rate') {
                $lists['value'] = json_decode($lists['value'], true);
            }
        }
        return view(null, [
            'list' => $list
        ]);
    }


    public function config_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'value' => 'require'
            ], [
                'name.require' => '名称不能为空',
                'value.require' => '路径不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($data['name'] == 'ptdatas') {
                $data['value'] = json_encode($data['value'], true);
            }
            if ($data['name'] == 'rate') {
                if (!isset($data['value']['allrate']) || !isset($data['value']['arearate']) || !isset($data['value']['cityrate']) || !isset($data['value']['streetrate'])) {
                    return json(['status' => 1, 'msg' => '参数设置错误']);
                }
                $data['value']['allrate'] = floor($data['value']['allrate'] * 100) / 100;
                $data['value']['arearate'] = floor($data['value']['arearate'] * 100) / 100;
                $data['value']['cityrate'] = floor($data['value']['cityrate'] * 100) / 100;
                if ($data['value']['allrate'] < ($data['value']['arearate'] + $data['value']['cityrate'] + $data['value']['streetrate'])) {
                    return json(['status' => 1, 'msg' => '请确保代理收益总和不超过商家抽成比例值']);
                }
                $data['value'] = json_encode($data['value'], true);
            }

            $res = (new Config())->allowfield(true)->save($data, ['name' => $data['name']]);
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 1, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('name', '');
            $row = (new Config())->where('name', $id)->find();
            if (!empty($row) && $row['name'] == 'rate') {
                $row['value'] = json_decode($row['value'], true);
            }
            if (!empty($row) && $row['name'] == 'ptdatas') {
                $row['value'] = json_decode($row['value'], true);
            }
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function rebot()
    {
        $list = (new Rebot())->order('id desc')->paginate(10);
        return view(null, [
            'list' => $list
        ]);
    }

    public function rebot_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'datas' => 'require'
            ], [
                'datas.require' => '数据不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            if (!empty($data['datas']['user'])) {
                $data['datas']['user'] = array_values($data['datas']['user']);
            }
            $id = $data['id'] ?? 0;
            $data['datas'] = json_encode($data['datas'], true);
            if (!empty($id)) {
                $res = (new Rebot())->allowfield(true)->save($data, ['id' => $id]);
            } else {
                $res = (new Rebot())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 1, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', '');
            $row = (new Rebot())->where('id', $id)->find();
            if ($row) {
                $row['datas'] = json_decode($row['datas'], true);
            }
            $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
            foreach ($shop as $k => $shops) {
                $area = (new BusinessArea())->where(['businessid' => $shops['id']])->find();
                // if (empty($area)) {
                //     unset($shop[$k]);
                //     continue;
                // }
                // $goods = (new Goods())->where(['businessid' => $shops['id'], 'isSale' => 1, 'isdel' => 1])->find();
                // if (empty($goods)) {
                //     unset($shop[$k]);
                //     continue;
                // }
            }
            return view('', [
                'row' => $row,
                'business' => $shop
            ]);
        }
    }
}
